package com.quartz.monitor4job.servlet;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.quartz.TriggerListener;
import org.quartz.impl.StdScheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.quartz.monitor4job.listener.MonitorTriggerListener;
import com.quartz.monitor4job.util.ApplicationUtil;

/**
 * quartz监控初始化servlet
 * @author LIPENG
 *
 * @date 2017年6月29日 上午10:41:48
 *
 * @version V1.0
 */
public class QuartzListenerInitServlet extends HttpServlet {

	private static final Logger logger = LoggerFactory.getLogger(QuartzListenerInitServlet.class);
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		 //获取ServletContext 再获取 WebApplicationContextUtils  
        ServletContext servletContext = this.getServletContext();  
        WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);  
        ApplicationUtil.setApplicationContext(context);
        System.out.println("Quartz 开始初始化...");  
        try {  
        	String quartzBeanName=config.getInitParameter("quartzBeanName");
            //启动调度  
        	StdScheduler stdScheduler = ApplicationUtil.getBean(quartzBeanName);  
            TriggerListener myListener=new MonitorTriggerListener();  
            stdScheduler.getListenerManager().addTriggerListener(myListener);
            System.out.println("名称为 " + stdScheduler.getSchedulerName() + "的任务调度启动正常");  
        } catch (Exception e) {  
            System.out.println("Quartz 初始化异常: " + e.toString());  
            logger.error("Quartz 初始化异常",e);  
        }  
        
	}

}
